<template>
  <div>
    <div id="mapContainer"></div>
    <el-select style="width: 65%;" v-model="selectedAddress" filterable remote :remote-method="searchPlaces"
      @change="handleAddressChange" placeholder="搜索地址">
      <el-option v-for="poi in searchResults" :key="poi.uid" :label="poi.title + ', ' + poi.address" :value="poi.uid" />
    </el-select>
  </div>
</template>

<script>
export default {
  props: {
    initialCoordinates: {
      type: Object,
      required: false,
      default: () => ({ lat: 39.915, lng: 116.404, address: "深圳市" }) // 默认坐标，可根据需要调整
    }
  },
  data () {
    return {
      selectedAddress: '',
      searchResults: [],
      localSearch: null,
      map: null,
      isLoading: false
    };
  },
  watch: {
    'initialCoordinates.lat': function (newLat, oldLat) {
      if (newLat !== oldLat) {
        this.updateMapCenter();
      }
    },
    'initialCoordinates.lng': function (newLng, oldLng) {
      if (newLng !== oldLng) {
        this.updateMapCenter();
      }
    },
    isLoading (nval, oval) {
      if (nval) {
        if (this.initialCoordinates && this.initialCoordinates.lat && this.initialCoordinates.lng) {
          this.map = new BMapGL.Map("mapContainer");
          const center = new BMapGL.Point(this.initialCoordinates.lng, this.initialCoordinates.lat);
          this.map.centerAndZoom(center, 11);
          // 创建 LocalSearch 实例
          this.localSearch = new BMapGL.LocalSearch(this.map, {
            onSearchComplete: this.displayResults
          });
          // 获取并显示初始坐标的地址
          this.getAddressFromCoordinates(this.initialCoordinates);
        } else {
          // 处理没有初始坐标或坐标信息不完整的情况
          console.error("Invalid initial coordinates");
        }
      }
    }
  },
  created () {
    this.loadBaiduMapScript()
  },
  methods: {
    commonMapCallback () {
      setTimeout(() => { this.isLoading = true, 3000 })
      // 百度地图API功能
      console.log('地图API加载完毕...');
    },
    loadBaiduMapScript () {
      // DVhRByRsGlv17w8GmULTp4ulztsb1bgi
      // OvPTtKXsF74jAMW5avPC9eAAVww3auWa
      console.log('开始加载地图API...');
      let that = this
      return new Promise((resolve, reject) => {
        const ak = 'DVhRByRsGlv17w8GmULTp4ulztsb1bgi'
        const callbackName = 'commonMapCallback'
        const script = document.createElement('script')
        script.src = `https://api.map.baidu.com/api?v=3.0&&type=webgl&&ak=${ak}&&callback=${callbackName}`
        document.body.appendChild(script)
        window[callbackName] = () => {
          that.commonMapCallback()
          resolve()
          delete window[callbackName]
        }
        script.onerror = (err) => {
          reject(err)
        }
      })
    },
    updateMapCenter () {
      if (this.map && this.initialCoordinates) {
        this.getAddressFromCoordinates(this.initialCoordinates)
      }
    },
    searchPlaces (query) {
      if (this.localSearch && query) {
        this.localSearch.search(query);
      } else {
        this.searchResults = [];
      }
    },
    displayResults (results) {
      if (this.localSearch.getStatus() == BMAP_STATUS_SUCCESS) {
        this.searchResults = [];
        for (var i = 0; i < results.getCurrentNumPois(); i++) {
          var poi = results.getPoi(i);
          this.searchResults.push({
            title: poi.title,
            address: poi.address,
            point: poi.point,
            uid: poi.uid
          });
        }
      } else {
        this.searchResults = [];
      }
    },
    selectPlace (poi) {
      console.log("Selected Place: ", poi.title, poi.point);
      // 处理选择的地点
    },
    handleAddressChange (value) {
      const selectedPoi = this.searchResults.find(poi => poi.uid === value);
      if (selectedPoi) {
        this.$emit('address-selected', selectedPoi);
        console.log("Selected Address Details: ", selectedPoi);
        // 在这里处理选择的地址的详细信息
      }
    },
    getAddressFromCoordinates (coordinates) {
      var geoc = new BMapGL.Geocoder();
      var point = new BMapGL.Point(coordinates.lng, coordinates.lat);
      geoc.getLocation(point, (result) => {
        if (coordinates.address) {
          this.selectedAddress = coordinates.address;
        } else if (result) {
          this.selectedAddress = result.address; // 设置地址到搜索栏
        }
      });
    }
  },
  mounted () { }
};
</script>

<style scoped>
#resultsList li {
  cursor: pointer;
  padding: 5px;
  border-bottom: 1px solid #ddd;
}

#resultsList li:hover {
  background-color: #f0f0f0;
}
</style>